import {inject, observer} from 'mobx-react';
import {routerShape} from 'react-router';
import {WeaTop, WeaTab, WeaLocaleProvider, WeaRightMenu, WeaTools,WeaAlertPage} from 'ecCom';
import {WeaTableNew} from "comsMobx";
import * as mobx from "mobx";
import {Button, Modal, message,Popover } from 'antd';
import {Condition, getAdButtons} from './Condition';
import * as API from "../../apis/standCustomReport";
import ExportInfo from './ExportInfo';

const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
const {ls} = WeaTools;

@inject('standardCustomReportStore')
@observer
export default class Main extends React.Component {
    static contextTypes = {
        router: routerShape
    }

    doInit(props){
        const {location = {}, standardCustomReportStore} = props;
        const {query = {}} = location;
        const {reportParamsKey = '', reportid} = query;
        const {search,title = ''} = standardCustomReportStore;
        let lsParams  = {};
        if (reportParamsKey) {
            lsParams = ls.getJSONObj(reportParamsKey) || {};
        }
        search({...lsParams,...query});
        if(typeof window.doThemeAction !== 'function' && title) document.title =  title;
    }

    componentDidMount() {
        const {standardCustomReportStore} = this.props;
        standardCustomReportStore.clearDatas();
        this.doInit(this.props)
    }

    componentWillReceiveProps(nextProps) {
        if(this.props.location.key !== nextProps.location.key) {
            const { standardCustomReportStore } = this.props;
            standardCustomReportStore.clearAllStatus();
            this.doInit(nextProps);
        }
    }

    componentWillUnmount() {
        const {location = {}, standardCustomReportStore} = this.props;
        const {query = {}} = location;
        const {dataKey} = standardCustomReportStore;
        const {reportParamsKey = '',reportid= ''} = query;
        if (reportParamsKey) {
            window.localStorage.removeItem(reportParamsKey);
        }
        standardCustomReportStore.clearDatas(false);

        const modeid = dataKey.split("_")[0].split("_")[1];
        const method = '0';
        const redefault = '1';
        const colSetParams = {method, reportid , modeid,redefault};
        if(modeid === "0"){
            API.tableColSet(colSetParams);
        }
    }

    render() {
        const {standardCustomReportStore} = this.props;
        const {tableStore, loading, exportExcelUrl = '', noRight = false, title = '',exportInfo = []} = standardCustomReportStore;
        return (
            <div style={{height:'100%',width:'100%'}}>
                {noRight ?
                    <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@mdkxgz`}>
                        <div>
                            {getLabel(382663, '暂无权限')}
                        </div>
                    </WeaAlertPage>
                    :
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@tqi4dx`}
                        collectParams={{favname: title, favouritetype: '2'}}
                        datas={this.getRightMenu()}
                    >
                        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@quhilm`} loading={loading} icon={<i className='icon-coms-workflow'/>} buttons={this.getButtons()}
                                iconBgcolor='#0079DE' title={title} showDropIcon={true}
                                dropMenuDatas={this.getRightMenu()}>
                            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@v9q0er`} comsWeaTableStore={tableStore} needScroll={true} tableWidth={this.getTableWidth}
                                      rowKey={(record, index) => {return `${record.requestid}_${record.detailRecordId || ""}_${index}`;}}
                                      stsStyle={{background: '#E7F3FC', color: '#4A7DA4', boxShadow: '0 1px 0 0 #AED4F1'}}
                                      stsAllStyle={{background: '##E8FEE8', color: '#488248', boxShadow: '0 1px 0 0 #B7DDB7'}}
                                      getColumns={this.getColumns.bind(this)}
                            />
                        </WeaTop>
                        <iframe name="exportExcel" src={exportExcelUrl} style={{display: 'none'}}></iframe>
                        {exportInfo.length > 0 && <ExportInfo ecId={`${this && this.props && this.props.ecId || ''}_ExportInfo@tddgwk`}/>}
                    </WeaRightMenu>
                }
            </div>
        )
    }

    getButtons() {
        const {standardCustomReportStore,location={}} = this.props;
        const {query = {}} = location;
        const {reportid} = query;
        const {exportExcel} = standardCustomReportStore;
        let btns = [];
        btns.push(
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oafdiq@search`} type="primary" onClick={() => this.goBack()}>{getLabel(383659, '重新搜索')}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@v3wazb@exportExcel`} type="primary" onClick={() => exportExcel(true,reportid)}>{getLabel(132190, '导出Excel')}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@p5smxa@colSet`} type="primary" onClick={() => this.doColSet()}>{getLabel(382660, '显示列定制')}</Button>),
            )
        return btns;
    }

    getTableWidth = (columns) => {
        let showLength = columns.filter((col) => col.display == 'true').length;
        return 10 * showLength + "%";//也支持返回固定值，如果小于100%,不会生效。
    }

    //收缩算法
    getColumns(columns) {
        // 处理返回的行
        columns = columns.map((col, colIndex) => {
            let newCol = {...col};
            let dataIndex = col.dataIndex;
            newCol.render = (text, record, index) => {
                //签字意见
                if ('signoption' == dataIndex) {
                    let valueSpan = record[dataIndex + "span"] !== undefined ? record[dataIndex + "span"] : '';
                    if(valueSpan == '') {
                        return (
                            <div></div>
                        )
                    } else {
                        let _tempValuespan = valueSpan;
                        _tempValuespan = _tempValuespan.replace(/<[^>]+>/g,'');
                        return (
                            <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@cfwwf6`} placement="bottomLeft" title={'意见'} content={this.getSignOptionContent(valueSpan)} trigger="hover">
                                <div className="wea-url noWrap" style={{'cursor':'pointer'}} dangerouslySetInnerHTML={{__html: _tempValuespan.replace(/@@@@\d.*?~~~~/g,' ')}}/>
                            </Popover>
                        )
                    }
                } else {
                    return col.render(text, record, index);
                }
            }
            return newCol;
        });
        return columns;
    }

    getSignOptionContent(content = ''){
        let contentArr = content.split(/@@@@\d.*?~~~~/);
        return (
            <ul style={{maxWidth:'300px',maxHeight:'200px',overflowX:'hidden'}}>
                { contentArr && contentArr.length > 0 &&
                    contentArr.map((v)=>{
                        return <li dangerouslySetInnerHTML={{__html:v}}/>
                    })
                }
            </ul>
        )
    }

    getRightMenu() {
        const {location = {}, standardCustomReportStore} = this.props;
        const {tableStore, exportExcel} = standardCustomReportStore;
        const {query = {}} = location;
        const {reportid} = query;
        let btns = [];
        btns.push(
            {
                key: "back",
                icon: <i className="icon-coms-go-back"/>,
                content: getLabel(383624, '返回'),
                onClick: key => {
                    this.goBack();
                }
            }, {
                key: "reSearch",
                icon: <i className="icon-coms-search"/>,
                content: getLabel(383659, '重新搜索'),
                onClick: key => {
                    this.goBack();
                }
            }, {
                key: "exportExcel",
                icon: <i className="icon-coms-plate"/>,
                content: getLabel(132190, '导出Excel'),
                onClick: key => {
                    exportExcel(true,reportid);
                }
            }, {
                key: "colSet",
                icon: <i className='icon-workflow-Right-menu-Custom'/>,
                content: getLabel(382660, '显示列定制'),
                onClick: key => {
                    this.doColSet();
                }
            }
        )
        return btns;
    }

    //显示列定制
    doColSet() {
        const {location = {}, standardCustomReportStore} = this.props;
        const {tableStore,tabKey} = standardCustomReportStore;
        tableStore.setColSetVisible(true);
        const {query = {}} = location;
        const {reportParamsKey = '', reportid} = query;
        if (reportParamsKey) {
            const params = ls.getJSONObj(reportParamsKey) || {};
            params['reportid'] = reportid;
            params['modeid'] = tabKey;
            tableStore.tableColSet(true, params,false, reportid);
        }
    }

    goBack() {
        const {location = {} ,standardCustomReportStore} = this.props;
        const {query = {}} = location;
        const {dataKey} = standardCustomReportStore;
        const {reportParamsKey = ''} = query;
        if (reportParamsKey) {
            const params = ls.getJSONObj(reportParamsKey) || {};
            window.localStorage.removeItem(reportParamsKey);
            delete query['reportParamsKey'];
        }

        query['tabKey'] = dataKey.split("_")[1];
        this.context.router.push({
            pathname: "/main/workflow/standardCustomViewReport",
            query
        });
    }
}